package com.wzl.day22;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Day22 {

    static class Person {
        private int id;
        private String name;
        /**
         * 用户所在的组
         */
        private int groupId;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getGroupId() {
            return groupId;
        }

        public void setGroupId(int groupId) {
            this.groupId = groupId;
        }

        public Person(int id, String name, int groupId) {
            this.id = id;
            this.name = name;
            this.groupId = groupId;
        }
    }

    public static void main(String[] args) {
//           4个学生在两个分组内
        Person p1 = new Person(1, "wu", 1);
        Person p2 = new Person(2, "zhi", 1);
        Person p3 = new Person(3, "de", 2);
        Person p4 = new Person(4, "xiao", 2);
        List<Person> allStudent = new LinkedList<>();
        allStudent.add(p1);
        allStudent.add(p2);
        allStudent.add(p3);
        allStudent.add(p4);

        String jsonStr = JSON.toJSONString(allStudent);
        System.out.println(jsonStr);
//        以组id为key，Person为value
        Map<Integer, List<Person>> studentMap = allStudent.stream().collect(Collectors.toMap(
                key -> key.getGroupId(),
                val -> {
                    List<Person> valList = new ArrayList();
                    valList.add(val);
                    return valList;
                },
                (List<Person> newValueList, List<Person> oldValueList) -> {
                    oldValueList.addAll(newValueList);
                    return oldValueList;
                }));

        String res = JSON.toJSONString(studentMap);
        System.out.println(res);

    }

}
